
package com.base.commons.tools.exception;


import com.base.commons.tools.utils.MessageUtils;
import lombok.Getter;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义异常
 *
 * @author carl
 * @since 1.0.0
 */
@Getter
public class BaseOfException extends RuntimeException {
	private static final long serialVersionUID = 1L;

    private Integer code;
	private String message;

	public BaseOfException(Integer code) {
		this.code = code;
		this.message = MessageUtils.getMessage(code)!=null ? MessageUtils.getMessage(code): "";
	}

/*String... params 表示 Object[0], Object[1], Object[2].....  Object[n]
没有走占位符的枚举，而且还未国际化的params[0] 表示message
* params[1-n] 表示表示占位符
* 如果国际化有：params[1-n] 表示表示占位符
* */
	public BaseOfException(Integer code, String... params) {
		this.code = code;
		if(MessageUtils.getMessage(code, params)==null){
			if(params.length==1){
				this.message = MessageUtils.getMessage(code, params)!=null? MessageUtils.getMessage(code, params):params[0];
			}else {
				    String[]  strObject=params.clone();
				     List<String>  sts=new ArrayList<>();
				    for(int i=0;i<strObject.length;i++){
				    	if(i!=0){
							sts.add(strObject[i]);
						}

					}
				this.message=MessageFormat.format(params[0],sts);
			}
		}else {
            this.message= MessageUtils.getMessage(code, params);
		}

	}

	public BaseOfException(Integer code, Throwable e) {
		super(e);
		this.code = code;
		this.message = MessageUtils.getMessage(code);
	}

	public BaseOfException(String message) {
		super(message);
		this.code = ErrorCode.INTERNAL_SERVER_ERROR;
		this.message = message;
	}

	public BaseOfException(String message, Throwable e) {
		super(message, e);
		this.code = ErrorCode.INTERNAL_SERVER_ERROR;
		this.message = message;
	}

	public BaseOfException(int code, Throwable e, String... params) {
		super(e);
		this.code = code;
		this.message = MessageUtils.getMessage(code, params);
	}
}